package com.wbdgj.ui.home;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bumptech.glide.Glide;
import com.google.gson.internal.LinkedTreeMap;
import com.igexin.sdk.PushManager;
import com.wbdgj.R;
import com.wbdgj.adapter.MessageAdapter;
import com.wbdgj.base.BaseActivity;
import com.wbdgj.base.BaseApplication;
import com.wbdgj.http.HttpAdapter;
import com.wbdgj.http.OnResponseListener;
import com.wbdgj.model.LngLat;
import com.wbdgj.model.ResultMessageObjectModel;
import com.wbdgj.model.ResultObjectModel;
import com.wbdgj.ui.login.LoginActivity;
import com.wbdgj.ui.mine.EwmActivity;
import com.wbdgj.ui.mine.VerifiedActivity;
import com.wbdgj.ui.mine.YjfkActivity;
import com.wbdgj.ui.news.News01Fragment;
import com.wbdgj.ui.news.News02Fragment;
import com.wbdgj.ui.news.News03Fragment;
import com.wbdgj.ui.news.NewsFragment;
import com.wbdgj.utils.CommonUtils;
import com.wbdgj.utils.CoodinateCovertor;
import com.wbdgj.utils.SpKeyUtils;
import com.wbdgj.utils.ToastUtils;
import com.wbdgj.utils.dialog.ConfirmDialog;
import com.wbdgj.utils.scrollablelayout.ScrollableLayout;
import com.wbdgj.views.NoScrollViewPager;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import retrofit2.Call;

/**
 * Created by Administrator on 2018/6/1.
 */

public class WbDetailActivity extends BaseActivity implements PtrHandler{

    private Context context = this;
    @BindView(R.id.pfl_root)
    PtrClassicFrameLayout pfl_root;
//    @BindView(R.id.sl_root)
//    ScrollableLayout sl_root;
    @BindView(R.id.ScrollView)
    ScrollView ScrollView;

    @BindView(R.id.destination_tab_layout)
    TabLayout mTabLayout;
    @BindView(R.id.destination_viewpager)
    NoScrollViewPager mViewPager;


    private MyFragmentPagerAdapter adapter;
    private List<Fragment> fragments;
    private WbDetail01Fragment WbDetail01Fragment;
    private WbDetail02Fragment WbDetail02Fragment;
    private WbDetail03Fragment WbDetail03Fragment;
    private WbDetail04Fragment WbDetail04Fragment;

    private String BRANCH_ID, DISTANCE;

    @BindView(R.id.name)
    TextView name;

    @BindView(R.id.ls)
    TextView ls;
    @BindView(R.id.ls2)
    TextView ls2;
    @BindView(R.id.ls3)
    TextView ls3;

    @BindView(R.id.money)
    TextView money;
    @BindView(R.id.jl)
    TextView jl;

    @BindView(R.id.address)
    TextView address;
    @BindView(R.id.btn_top_right)
    ImageView btn_top_right;

    @BindView(R.id.mdImg)
    ImageView mdImg;

    private String phone;

    private String branch_coord, zoneName, TYPE;
    private String COORDSX, COORDSY;

    @BindView(R.id.convenientBanner)
    ConvenientBanner convenientBanner;
    private ArrayList<String> localImages = new ArrayList<String>();

    @Override
    protected int getLayoutResId() {
        return R.layout.ui_wb_detail;
    }

    @Override
    protected void initView() {
        BRANCH_ID = getIntent().getStringExtra("id");
        DISTANCE = getIntent().getStringExtra("DISTANCE");
        ScrollView.scrollTo(0, 0);
        if (TextUtils.isEmpty(DISTANCE)){
            jl.setVisibility(View.GONE);
        }else{
            jl.setVisibility(View.VISIBLE);
        }
        jl.setText(">"+DISTANCE+"m");
        queryBranch();
        pfl_root.setEnabledNextPtrAtOnce(true);
        pfl_root.setLastUpdateTimeRelateObject(this);
        pfl_root.setPtrHandler(this);
        pfl_root.setKeepHeaderWhenRefresh(true);
        pfl_root.disableWhenHorizontalMove(true);
//        sl_root.getHelper().setCurrentScrollableContainer(ScrollView);
        fragments = new ArrayList<>();
        fragments.add(WbDetail02Fragment = (WbDetail02Fragment)Fragment.instantiate(context,WbDetail02Fragment.class.getName()));
        fragments.add(WbDetail01Fragment = (WbDetail01Fragment) Fragment.instantiate(context,WbDetail01Fragment.class.getName()));
        fragments.add(WbDetail03Fragment = (WbDetail03Fragment)Fragment.instantiate(context,WbDetail03Fragment.class.getName()));
        fragments.add(WbDetail04Fragment = (WbDetail04Fragment)Fragment.instantiate(context,WbDetail04Fragment.class.getName()));
        adapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
        mViewPager.setAdapter(adapter);

        mTabLayout.setupWithViewPager(mViewPager);
        listAll();
        mTabLayout.getTabAt(0).setText("门店活动");
        mTabLayout.getTabAt(1).setText("门店信息");
//        mTabLayout.getTabAt(2).setText("留言区");
        mTabLayout.getTabAt(3).setText("特色服务");

    }

    @OnClick({R.id.dh, R.id.wylyLay, R.id.phone, R.id.dhLay, R.id.btn_top_right})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.dh:
                if (TextUtils.isEmpty(COORDSX)){
                    Uri uri = Uri.parse("amapuri://route/plan/?dlat="+""+"&dlon="+""+"&dname="+name.getText().toString()+"&dev=0&t=0");
                    startActivity(new Intent(Intent.ACTION_VIEW, uri));
                }else{
                    startActivity(new Intent(context, MapDialogAtivity.class).putExtra("COORDSX", COORDSX).putExtra("COORDSY", COORDSY));
                }
                break;
            case R.id.wylyLay:
                getMbUserInfo();
                break;
            case R.id.btn_top_right:
                if (TYPE.equals("")){
                    final ConfirmDialog confirmDialog = new ConfirmDialog(context, "确定关注吗？", 1);
                    confirmDialog.show();
                    confirmDialog.setCanceledOnTouchOutside(false);
                    confirmDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
                        @Override
                        public void doConfirm() {
                            confirmDialog.dismiss();
                            addAttention();
                        }

                        @Override
                        public void doCancel() {
                            confirmDialog.dismiss();
                        }
                    });
                }else{
                    final ConfirmDialog confirmDialog = new ConfirmDialog(context, "确定取消关注吗？", 1);
                    confirmDialog.show();
                    confirmDialog.setCanceledOnTouchOutside(false);
                    confirmDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
                        @Override
                        public void doConfirm() {
                            confirmDialog.dismiss();
                            delAttention();
                        }

                        @Override
                        public void doCancel() {
                            confirmDialog.dismiss();
                        }
                    });
                }
                break;
            case R.id.dhLay:
                if (TextUtils.isEmpty(COORDSX)){
                    Uri uri = Uri.parse("amapuri://route/plan/?dlat="+""+"&dlon="+""+"&dname="+name.getText().toString()+"&dev=0&t=0");
                    startActivity(new Intent(Intent.ACTION_VIEW, uri));
                }else{
                    startActivity(new Intent(context, MapDialogAtivity.class).putExtra("COORDSX", COORDSX).putExtra("COORDSY", COORDSY));
                }
                break;
            case R.id.phone:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (ContextCompat.checkSelfPermission(context,
                            Manifest.permission.CALL_PHONE)
                            != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, 10);
                    }else{
                        Intent intent =new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+phone));
                        startActivity(intent);
                    }
                }else{
                    Intent intent =new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+phone));
                    startActivity(intent);
                }
                break;
        }
    }

    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
//        if (sl_root.isCanPullToRefresh()) {
//            return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
//        }
//        return false;
        return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        pfl_root.refreshComplete();
        queryBranch();
    }


    private class MyFragmentPagerAdapter extends FragmentPagerAdapter {
        public MyFragmentPagerAdapter(FragmentManager fm) {
            super(fm);

        }
        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }
    }

    private void queryBranch() {
        Call<ResultObjectModel> call = HttpAdapter.getSerives().queryBranch(BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.TOKEN), BRANCH_ID);
        call.enqueue(new OnResponseListener<ResultObjectModel>(context) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    DecimalFormat decimalFormat = new DecimalFormat("###################.###########");
                    LinkedTreeMap linkedTreeMap = (LinkedTreeMap) userModelBaseResultModel.getData();
                    name.setText(linkedTreeMap.get("NAME")+"");
                    address.setText(linkedTreeMap.get("ADDRESS")+"");
                    if (!(linkedTreeMap.get("BRANCH_AVG")+"").equals("null")){
                        money.setText("人均"+decimalFormat.format(linkedTreeMap.get("BRANCH_AVG"))+"元/小时");
                    }
                    if (linkedTreeMap.containsKey("TAB")){
                        String[] split = (linkedTreeMap.get("TAB")+"").split(",");
                        if (split.length == 1){
                            ls.setVisibility(View.VISIBLE);
                            ls2.setVisibility(View.GONE);
                            ls3.setVisibility(View.GONE);
                           ls.setText(split[0]);
                        }
                        if (split.length == 2){
                            ls.setVisibility(View.VISIBLE);
                            ls2.setVisibility(View.VISIBLE);
                            ls3.setVisibility(View.GONE);
                            ls.setText(split[0]);
                            ls2.setText(split[1]);
                        }
                        if (split.length == 3){
                            ls.setVisibility(View.VISIBLE);
                            ls2.setVisibility(View.VISIBLE);
                            ls3.setVisibility(View.VISIBLE);
                            ls.setText(split[0]);
                            ls2.setText(split[1]);
                            ls3.setText(split[2]);
                        }
                    }else{
                        ls.setVisibility(View.VISIBLE);
                        ls.setText("单体门店");
                        ls2.setVisibility(View.GONE);
                        ls3.setVisibility(View.GONE);
                    }
                    if (linkedTreeMap.containsKey("COORDSY")){
                        COORDSY =  linkedTreeMap.get("COORDSY")+"";
                    }
                    if (linkedTreeMap.containsKey("COORDSX")){
                        COORDSX =  linkedTreeMap.get("COORDSX")+"";
                    }
                    zoneName = linkedTreeMap.get("NAME") +"";
                    if (linkedTreeMap.containsKey("BRANCH_PHONE")){
                        phone = linkedTreeMap.get("BRANCH_PHONE") +"";
                    }
                    if ((linkedTreeMap.get("TYPE")+"").equals("null")){
                        TYPE = "";
                        btn_top_right.setImageResource(R.mipmap.gz_no);
                    }else{
                        TYPE = "1";
                        btn_top_right.setImageResource(R.mipmap.gz_yes);
                    }

                    if (!(linkedTreeMap.get("IMG_URL_ONE")+"").equals("null")){
                        Glide.with(context).load(HttpAdapter.HEAD_URL+linkedTreeMap.get("IMG_URL_ONE")).placeholder(R.mipmap.detail_wait).error(R.mipmap.detail_error).into(mdImg);
                    }

                    localImages = new ArrayList<>();
                    if (linkedTreeMap.containsKey("IMG_URL_ONE")){
                        localImages.add(HttpAdapter.HEAD_URL +linkedTreeMap.get("IMG_URL_ONE"));
                    }
                    if (linkedTreeMap.containsKey("IMG_URL_TWO")){
                        localImages.add(HttpAdapter.HEAD_URL +linkedTreeMap.get("IMG_URL_TWO"));
                    }
                    if (linkedTreeMap.containsKey("IMG_URL_THREE")){
                        localImages.add(HttpAdapter.HEAD_URL +linkedTreeMap.get("IMG_URL_THREE"));
                    }
                    if (linkedTreeMap.containsKey("IMG_URL_FOUR")){
                        localImages.add(HttpAdapter.HEAD_URL +linkedTreeMap.get("IMG_URL_FOUR"));
                    }

                    convenientBanner.setPages(new CBViewHolderCreator() {
                        @Override
                        public Object createHolder() {
                            return new LocalImageHolderView();
                        }
                    },localImages)
                            //设置指示器是否可见
                            .setPointViewVisible(true)
                            //设置自动切换（同时设置了切换时间间隔）
                            .startTurning(3000)
                            //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                            .setPageIndicator(new int[]{R.mipmap.ic_page_indicator, R.mipmap.ic_page_indicator_focused})
                            //设置指示器的方向（左、中、右）
                            .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                            //设置点击监听事件
                        //                .setOnItemClickListener(this)
                            //设置手动影响（设置了该项无法手动切换）
                            .setManualPageable(true);
                    if (localImages.size() == 0){
                        mdImg.setVisibility(View.VISIBLE);
                        convenientBanner.setVisibility(View.GONE);
                    }else{
                        mdImg.setVisibility(View.GONE);
                        convenientBanner.setVisibility(View.VISIBLE);
                    }
                }else if (userModelBaseResultModel.getResultCode().equals("1111")){
                    ToastUtils.toastShort("账号没有登录或在其它地方登录");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, "");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "2");
                    PushManager.getInstance().unBindAlias(context, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.LOGIN_PHONE), false, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CID));
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }else{
                    ToastUtils.toastShort(userModelBaseResultModel.getResultMsg());
                }
            }
        });
    }

    private void addAttention() {
        Call<ResultObjectModel> call = HttpAdapter.getSerives().addAttention(BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.TOKEN), BRANCH_ID);
        call.enqueue(new OnResponseListener<ResultObjectModel>(context) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    ToastUtils.toastShort("关注成功！");
                    queryBranch();
                }else if (userModelBaseResultModel.getResultCode().equals("1111")){
                    ToastUtils.toastShort("账号没有登录或在其它地方登录");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, "");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "2");
                    PushManager.getInstance().unBindAlias(context, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.LOGIN_PHONE), false, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CID));
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }else{
                    ToastUtils.toastShort(userModelBaseResultModel.getResultMsg());
                }
            }
        });
    }

    private void delAttention() {
        Call<ResultObjectModel> call = HttpAdapter.getSerives().delAttention(BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.TOKEN), BRANCH_ID);
        call.enqueue(new OnResponseListener<ResultObjectModel>(context) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    ToastUtils.toastShort("取消关注成功！");
                    queryBranch();
                }else if (userModelBaseResultModel.getResultCode().equals("1111")){
                    ToastUtils.toastShort("账号没有登录或在其它地方登录");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, "");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "2");
                    PushManager.getInstance().unBindAlias(context, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.LOGIN_PHONE), false, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CID));
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }else{
                    ToastUtils.toastShort(userModelBaseResultModel.getResultMsg());
                }
            }
        });
    }

    private void listAll() {
        Call<ResultMessageObjectModel> call = HttpAdapter.getSerives().msgList("", "5", "1",BRANCH_ID, "", "", "3");
        call.enqueue(new OnResponseListener<ResultMessageObjectModel>(context) {
            @Override
            protected void onSuccess(ResultMessageObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getCode() == 200){
                    mTabLayout.getTabAt(2).setText("留言区("+userModelBaseResultModel.getTotal()+")");
                }else{
                    ToastUtils.toastShort(userModelBaseResultModel.getMsg());
                }
            }
        });
    }

    //为了方便改写，来实现复杂布局的切换
    private class LocalImageHolderView implements Holder<String> {
        private ImageView imageView;

        @Override
        public View createView(Context context) {
            //你可以通过layout文件来创建，不一定是Image，任何控件都可以进行翻页
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, int position, String data) {
            Glide.with(context).load(data).placeholder(R.mipmap.detail_wait).error(R.mipmap.detail_error).into(imageView);
        }
    }

    private void getMbUserInfo() {
        Call<ResultObjectModel> call = HttpAdapter.getSerives().getMbUserInfo(BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.TOKEN));
        call.enqueue(new OnResponseListener<ResultObjectModel>(context) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    DecimalFormat decimalFormat = new DecimalFormat("###################.###########");
                    LinkedTreeMap linkedTreeMap = (LinkedTreeMap) userModelBaseResultModel.getData();
                    if ((linkedTreeMap.get("NAME")+"").equals("null")){
                        launch(VerifiedActivity.class);
                    }else if((linkedTreeMap.get("NAME")+"").equals("")){
                        launch(VerifiedActivity.class);
                    }else{
                        startActivity(new Intent(context, MessageActivity.class).putExtra("id", BRANCH_ID));
                    }

                }else if (userModelBaseResultModel.getResultCode().equals("1111")){
                    ToastUtils.toastShort("账号没有登录或在其它地方登录");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, "");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "2");
                    PushManager.getInstance().unBindAlias(context, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.LOGIN_PHONE), false, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CID));
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }
            }
        });
    }

}
